const express = require('express')
const router = express.Router()
const connection = require('.././mysql')


//! 获取商品 
router.get('/getGoodsList', (req, res) =>{
    const sql = 'SELECT * FROM goodslist'
    connection.query(sql, (err, result) => {
        if (err) return res.status(500).send('database error')
        if (result.length === 0) return res.status(404).send('not found')
        res.send({
            status: 200,
            msg:"获取商品列表成功",
            data: result
        })
    })
})

//! 删除商品
router.post('/deleteGoods', (req, res ) =>{
    const g_id = req.body.params.g_id
    const sql = `DELETE FROM goodslist WHERE g_id = '${g_id}'`

    connection.query(sql, (err, result) =>{
        if (err) {
            res.status(500).send('database error')
            console.log(err);
        } 
        if (result.affectedRows > 0){
            res.send({
                status: 200,
                msg: "删除商品成功"
            })
        }else{
            res.status(404).send('not found')
        }
    })
})

//! 新增商品
router.post('/addGoods', (req, res) =>{
    console.log(req.body.params);
    let { g_id, g_name, g_content, g_price, g_num, imgUrl } = req.body.params.info
    
    const sql = `INSERT INTO goodslist (g_id, g_name, g_content, g_price, g_num, imgUrl) VALUES ('${g_id}', '${g_name}', '${g_content}', '${g_price}', '${g_num}', '${imgUrl}')`

    connection.query(sql, (err, result) => {

        if (err){
            res.status(500).send('database error')
        } 
        if (result.affectedRows > 0){
            res.send({
                status: 200,
                msg: "新增商品成功"
            })
        }else{
            res.status(404).send('not found')
        }
    })
})



module.exports = router